import http from "../../request/http"
import {
  shopAip,
  checkOrder
} from "../../request/user"

// pages/pay/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart: [],
    address: {},
    totalNum: 0,
    totalPrice: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let carts = wx.getStorageSync('cart')
    let address = wx.getStorageSync('address')
    let cart = carts.filter(item => item.checked)
    let totalNum = 0
    let totalPrice = 0
    cart.forEach(item => {
      totalPrice += item.goods_price * item.num
      totalNum += item.num
    })
    this.setData({
      address,
      cart,
      totalNum,
      totalPrice
    })
  },

  async onClickButton() {
    //判断有没有token
    let token = wx.getStorageSync('token')
    if (!token) {
      wx.navigateTo({
        url: '../my/index',
      })
      return
    }

    let {
      cart,
      address,
      totalPrice
    } = this.data
    let arr = []
    cart.forEach(item => {
      arr.push({
        "goods_id": item.goods_id,
        "goods_number": item.num,
        "goods_price": item.goods_price
      })
    })

    let res = await http('/my/orders/create', {
      method: "POST",
      data: {
        "order_price": totalPrice,
        "consignee_addr": address.all,
        "goods": arr,
      }
    })
    console.log(res);
    if (res.meta.status == 200) {
      console.log(res, 88);
      let order_number = res.message.order_number
      const ress = await http('/my/orders/req_unifiedorder', {
        method: "POST",
        data: {
          "order_number": order_number
        }
      })
      //生产预支付信息
      console.log(97, ress);
      if (ress.meta.status == 200) {
        let {
          pay
        } = ress.message
        console.log('pay', pay)
        // 拉取微信的支付窗口
        wx.requestPayment({
          ...pay,
          // 如果有权限将拉取成功
          success(res) {
            console.log(res,'拉取成功');
          },
          // 没有权限则拉取失败
          fail(err) {
            console.log(err,'拉取失败');
          }
        })
      }

      //  查看是否支付状态
      const reses=await http('/my/orders/chkOrder',{data:{"order_number":order_number	},method:"POST"})
      console.log(reses,'120');
      if(reses.meta.status==400){
        wx.showToast({
          title: '支付成功',
        })
        wx.navigateTo({
          url: '../order/order',
        })
      }else{
        wx.showToast({
          title: '支付失败',
        })
      }
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})